package ch.ethz.group3.myalbum.server;

import java.util.Collection;

import ch.ethz.group3.myalbum.client.PictureService;
import ch.ethz.group3.myalbum.server.flickr.FlickrDAO;
import ch.ethz.group3.myalbum.server.utils.Converter;
import ch.ethz.group3.myalbum.shared.AuthorizationModel;
import ch.ethz.group3.myalbum.shared.CommentModel;
import ch.ethz.group3.myalbum.shared.GroupModel;
import ch.ethz.group3.myalbum.shared.ImageModel;
import ch.ethz.group3.myalbum.shared.InvalidFlickrTokenException;
import ch.ethz.group3.myalbum.shared.TokenModel;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class PictureServiceImpl extends RemoteServiceServlet implements
		PictureService {

	private FlickrDAO flickr;

	public PictureServiceImpl() {
		this.flickr = new FlickrDAO();
	}

	@Override
	public Collection<ImageModel> getAlbum(String groupId, int pageLimit,
			int page, TokenModel token) throws InvalidFlickrTokenException {
		try {
			if (flickr.isValidToken(token)) {
				return Converter.imagesModelFromFlickrPhotos(flickr
						.getPhotosByGroupId(groupId, pageLimit, page, token));
			}
		} catch (Exception e) {
		}
		InvalidFlickrTokenException e = new InvalidFlickrTokenException();
		e.setAuthorization(flickr.getAuthModel());
		throw e;
	}

	@Override
	public Collection<GroupModel> getGroups(String tags, int pageLimit,
			int page, TokenModel token) throws InvalidFlickrTokenException {
		try {
			if (flickr.isValidToken(token)) {
				return Converter.groupsModelFromFlickrGroups(flickr.getGroups(
						tags, pageLimit, page, token));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		InvalidFlickrTokenException e = new InvalidFlickrTokenException();
		e.setAuthorization(flickr.getAuthModel());
		throw e;
	}

	@Override
	public Collection<CommentModel> getComments(String photoId, TokenModel token)
			throws InvalidFlickrTokenException {
		try {
			if (flickr.isValidToken(token)) {
				return Converter.commentsModelFromFlickrComments(flickr
						.getComments(photoId, token));
			}
		} catch (Exception e) {
		}
		InvalidFlickrTokenException e = new InvalidFlickrTokenException();
		e.setAuthorization(flickr.getAuthModel());
		throw e;
	}

	@Override
	public TokenModel verify(String verifierString, TokenModel requestToken) {
		return flickr.verify(requestToken, verifierString);
	}
	
	@Override
	public AuthorizationModel getAuthorization() {
		return flickr.getAuthModel();
	}
}
